import { Popup, CheckList, Form } from 'antd-mobile'
import style from './index.module.less'
import { CloseCircleFill } from 'antd-mobile-icons'
import { useEffect, useState } from 'react'


function Line ({ data }) {
  return (
    <div className={style.item}>
      <div className={style['item-inner']}>
        <span>{data}</span>
      </div>
    </div>
  )
}

function Inner ({ value = [], onChange = () => {}, options = [], visible, setVisible, onDecide }) {
  const [v, setV] = useState([])
  useEffect(() => {
    if (visible && value.length) {
      setV([...value])
    }
  }, [value, visible])
  useEffect(() => {
    if (!visible) {
      setV([])
    }
  }, [visible])
  return (
    <>
      <div className={style.container}>
        <div className={style.list}>
          {
            value.map((v, i) => {
              return <Line key={i} data={v} index={i} />
            })
          }
        </div>
      </div>
      <Popup visible={visible} bodyStyle={{ height: '50vh' }} onMaskClick={() => setVisible(false)} position='bottom'>
        <div className={style.pop}>
          <div className={style.header}>
            <a onClick={() => setVisible(false)}>取消</a>
            <a onClick={() => { const l = [...v]; onChange(l); onDecide(l); setVisible(false) }}>确定</a>
          </div>
          <div className={style.body}>
            <div className={style.inner} onClick={(e) => { e.stopPropagation() }}>
              <CheckList value={v} multiple onChange={(v) => { setV(v) }}>
                {
                  options.map((v, i) => {
                    return <CheckList.Item key={i} value={v}>{v}</CheckList.Item>
                  })
                }
              </CheckList>
            </div>
          </div>
        </div>
      </Popup>
    </>
  )
}

function Main ({ name, label, rules, formRef, options = [], onChange = () => {} }) {
  const [visible, setVisible] = useState(false)
  return (
    <Form.Item name={name} label={label} rules={rules} onClick={() => { setVisible(true) }}>
      <Inner options={options} formRef={formRef} visible={visible} setVisible={setVisible} onDecide={onChange} />
    </Form.Item>
  )
}

export default Main
